package com.dzu.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author ZhaoDong
 * @date 2022/9/29 10:27
 * @description 151. 反转字符串中的单词
 */
public class Test151 {

    public static void main(String[] args) {
        System.out.println(reverseWords("a good   example"));
    }


    // 官方12ms
    public static String reverseWords2(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);

    }


        // 6ms
    public static String reverseWords(String s) {

        int length = s.length();

        List<String> list = new ArrayList<>(length);

        for (int end = 0; end < length; end++) {
            if (s.charAt(end) == ' ') {
                continue;
            }
            int start = end;
            StringBuilder temp = new StringBuilder();
            while (start < length && s.charAt(start) != ' ' ) {
                temp.append(s.charAt(start));
                start++;
            }
            list.add(temp.toString());
            end = start;

        }

        Collections.reverse(list);

        return String.join(" ", list);

    }
}
